package cn.itcast.web;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            //1.获取请求参数method
            String methodName = req.getParameter("method");
            //2设置默认方法名
            if (methodName == null) {
                methodName = "execute";
            }
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //3执行方法
            String jspPath = (String) method.invoke(this, req, resp);
            //4如果子类有返回值，将请求到指定的jsp中
            if (jspPath != null) {
                req.getRequestDispatcher(jspPath).forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("execute");
        return null;
    }
}
